// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/common/base/compare_flags.h>
#include <pollux/functions/macros.h>

namespace kumo::pollux::functions {
    // Returns NULL if
    // - input value is NULL
    // - in-list is NULL or empty
    // - input value doesn't have an exact match, but has an indeterminate match in
    // the in-list. E.g., 'array[null] in (array[1])', 'array[1] in (array[null])',
    // or '1 in (null)'.
    template<typename TExec>
    struct GenericInPredicateFunction {
        POLLUX_DEFINE_FUNCTION_TYPES(TExec);

        MELON_ALWAYS_INLINE bool callNullable(
            bool &result,
            const arg_type<Generic<T1> > *value,
            const arg_type<Variadic<Generic<T1> > > *inList) {
            if (value == nullptr || inList == nullptr) {
                return false; // NULL result.
            }

            if (inList->size() == 0) {
                return false;
            }

            const static auto compareFlag = CompareFlags::equality(
                CompareFlags::NullHandlingMode::kNullAsIndeterminate);
            bool hasNull = false;
            for (const auto &v: *inList) {
                if (v.has_value()) {
                    auto compareResult = value->compare(v.value(), compareFlag);
                    if UNLIKELY(!compareResult.has_value()) {
                        hasNull = true;
                        continue;
                    }
                    if (compareResult.value() == 0) {
                        result = true;
                        return true; // Non-NULL result.
                    }
                } else {
                    hasNull = true;
                }
            }
            if (hasNull) {
                return false;
            } else {
                result = false;
                return true;
            }
        }
    };
} // namespace kumo::pollux::functions
